package com.sample.kotlin

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.sample.base.utils.CacheUtils
import com.sample.kotlin.entity.User
import kotlinx.android.synthetic.main.activity_main.*

private val usernameKey = "username"
private val passwordKey = "password"

class MainActivity : AppCompatActivity(), View.OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        userName.setText(CacheUtils.get(usernameKey))
        pwd.setText(CacheUtils.get(passwordKey))

        codeView.setOnClickListener(this)
        btnLogin.setOnClickListener(this)
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.codeView -> {
                codeView.updateCode()
            }
            R.id.btnLogin -> {
                login()
            }
            else -> {
            }
        }
    }

    private fun login() {
        val user = User(
            userName = userName.text.toString(),
            password = pwd.text.toString(),
            code = etCode.text.toString()
        )
        if (verify(user)) {
            CacheUtils.save(usernameKey, userName.text.toString())
            CacheUtils.save(passwordKey, pwd.text.toString())
        }
    }

    private fun verify(user: User): Boolean {
        if (user.userName?.length ?: 0 < 4) {
            return false
        }
        if (user.password?.length ?: 0 < 4) {
            return false
        }
        return true
    }
}
